package com.dongman.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/***
 * steam爬虫
 */
@Log4j2
public class SteamSpider {
    private static final String ipUrl  = "http://tiqu.py.cn/getProxyIp?num=1&regions=us&lb=1&return_type=json&protocol=http";
    private static final String localIp  = "127.0.0.1";
    private static final Integer localPort  = 33210;

    public static JSONObject getProxyIp(String full_url) {
            JSONObject result1 = null;
            int ipTryTimes = 0;
            while (true) {
                String result = "";
                BufferedReader in = null;
                try {
                    java.net.URL connURL = new java.net.URL(full_url);
                    java.net.HttpURLConnection httpConn2 = (java.net.HttpURLConnection) connURL.openConnection();
                    httpConn2.connect();
                    in = new BufferedReader(new InputStreamReader(httpConn2.getInputStream(), "UTF-8"));
                    String line;
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                    JSONObject ipResult = JSONObject.parseObject(result);
                    System.out.println("代理IP返回值：" + ipResult);
                    String success = ipResult.getString("code");
                    String msg = ipResult.getString("msg");
                    if (!"0".equals(success)) {
                        System.out.println("代理IP未获取到，失败原因：" + msg + ", 然后沉睡三秒继续尝试获取, 已经尝试第“"+ipTryTimes+"”次");
                        Thread.sleep(3000);
                        ipTryTimes = ipTryTimes + 1;
                        continue;
                    }
                    JSONObject data = (JSONObject) ipResult.getJSONArray("data").get(0);
                    return data;
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                return result1 ;
            }
    }

    /**
     * @param full_url 请求地址
     * @param localDaili 是否本地代理
     * @return
     */
    public static String sendGet(String full_url, boolean localDaili) {
        String result="";
        int tryTimes = 0;
        int maxTryTimes = 10;
        while (tryTimes <= maxTryTimes) {
            String ip;
            Integer port;
            if (localDaili) {
                ip = localIp;
                port = localPort;
            } else {
                JSONObject ipObj = getProxyIp(ipUrl);
                ip = ipObj.getString("ip");
                port = ipObj.getIntValue("port");
            }
            BufferedReader in = null;
            try {
                java.net.URL connURL = new java.net.URL(full_url);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
                java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection(proxy);
                httpConn.setRequestProperty("Accept", "*/*");
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
                httpConn.setRequestProperty("cookie", "sessionid=50bb4cfe0e87068c63eea8da; steamCountry=JP%7C8f8b158ef9d6be56bff77956fbd14404; timezoneOffset=28800,0; _ga=GA1.2.2117376782.1678964936; _gid=GA1.2.155937934.1678964936; steamLoginSecure=76561199483128348%7C%7CeyAidHlwIjogIkpXVCIsICJhbGciOiAiRWREU0EiIH0.eyAiaXNzIjogInI6MEQxQ18yMjNBOTkzOF8yRjIwMyIsICJzdWIiOiAiNzY1NjExOTk0ODMxMjgzNDgiLCAiYXVkIjogWyAid2ViIiBdLCAiZXhwIjogMTY3OTA1Nzc4OCwgIm5iZiI6IDE2NzAzMzA2NTAsICJpYXQiOiAxNjc4OTcwNjUwLCAianRpIjogIjBEMjNfMjIzQTk5MzVfMjg4RDMiLCAib2F0IjogMTY3ODk3MDY0OSwgInJ0X2V4cCI6IDE2OTcwMDAzMTEsICJwZXIiOiAwLCAiaXBfc3ViamVjdCI6ICIxMDMuMTc2LjE5Ni4xNjUiLCAiaXBfY29uZmlybWVyIjogIjEwMy4xNzYuMTk2LjE2NSIgfQ.7GgqbS64K97sHalqSM3fBA8FJaY5JCobHnWsfq-46XvaURGurcU65VGVC0OGgmC8zirnEBezInC4gUPVx_ZKBA; browserid=2764686530205070235; webTradeEligibility=%7B%22allowed%22%3A1%2C%22allowed_at_time%22%3A0%2C%22steamguard_required_days%22%3A15%2C%22new_device_cooldown_days%22%3A0%2C%22time_checked%22%3A1678970682%7D; strInventoryLastContext=730_2");

                // 建立实际的连接
                httpConn.connect();

                int statusCode = httpConn.getResponseCode();

                if (statusCode != 200) {
                    System.out.println("返回码不是 200， 尝试重新请求");
                    Thread.sleep(3000);
                    tryTimes+=1;
                    continue;
                }
                //定义BufferedReader输入流来读取URL的响应,并设置编码方式
                in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return result ;
    }

    /**
     * 获取 求购记录
     * @param itemNameId
     */
    public static JSONArray getQiuGouJiLuByItemNameId(String itemNameId) {
        String qiugouUrl = "https://steamcommunity.com/market/itemordershistogram?country=US&language=schinese&currency=1&item_nameid="+itemNameId+"&two_factor=0";
        System.out.println("开始请求求购, url:" + qiugouUrl);
        String recordResult = sendGet(qiugouUrl, true);
        JSONObject qiuGouObj = JSONObject.parseObject(recordResult);
        System.out.println("itemNameId 返回值:" + qiuGouObj);
        JSONArray buyRecords = qiuGouObj.getJSONArray("buy_order_graph");
        int beforeSum = 0;
        JSONArray resultRecords = new JSONArray();
        for(int i=0;i<buyRecords.size();i++) {
            com.alibaba.fastjson2.JSONArray record = (com.alibaba.fastjson2.JSONArray) buyRecords.get(i);
            BigDecimal price = (BigDecimal) record.get(0);
            Integer num = (Integer) record.get(1);

            JSONObject one = new JSONObject();
            if (i == 0) {
                System.out.println("价格：" + price + "， 数量：" + num);
            }else {
                System.out.println("价格：" + price + "， 数量：" + (num - beforeSum));
            }
            one.put("price", price);
            one.put("num", num);
            resultRecords.add(one);
            beforeSum = num;
        }
        return resultRecords;
    }
    /**
     * 获取当itemNameId
     * @param baseUrl
     */
    public static String getItemNameIdByLink(String baseUrl) {
        String itemNameId = "";
        // ItemActivityTicker.Start( 176321160 );
        System.out.println("开始请求itemNameId, url:" + baseUrl);
        String itemNameResult = sendGet(baseUrl, true);
        Pattern pattern = Pattern.compile("ItemActivityTicker.Start\\( .* \\);");
        Matcher matcher = pattern.matcher(itemNameResult);
        while (matcher.find()){
            String aa[] = matcher.group().split("\\(");
            itemNameId = aa[aa.length - 1].replace(")", "").replace(";", "").trim();
            break;
        }
        System.out.println("itemNameId 返回值:" + itemNameId);
        return itemNameId;
    }
    /**
     * 获取当日成交量
     * @param baseUrl
     */
    public static String getVolumnByLink(String baseUrl) {
        String volume = "0";
        System.out.println("开始请求当日销售成交量, url:" + baseUrl);
        try {
            baseUrl = URLDecoder.decode(baseUrl, Charset.defaultCharset().displayName());
            String[] rr  =baseUrl.split("\\/");
            String appid = rr[5];
            String marketName = URLEncoder.encode(rr[6], Charset.defaultCharset().displayName());
            String volumUrl = "https://steamcommunity.com/market/priceoverview/?country=US&currency=1&appid="+appid+"&market_hash_name=" + marketName;
            System.out.println("当日销售成交量实际接口, url:" + baseUrl);
            String response = sendGet(volumUrl, true);
            System.out.println("当日销售成交量接口返回值:" + response);
            JSONObject result = JSONObject.parseObject(response);
            volume = result.getString("volume");
            volume = volume == null ? "0" : volume.replace(",", "");
            System.out.println("marketName:" + marketName + ", appid: " + appid + ", volume:  " + volume + "\n");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return volume;
    }


    public static void main(String[] args) {
        for (int i=0; i<1000;i++) {
            System.out.println(i);

            //带不带cookie都会封IP
            getQiuGouJiLuByItemNameId("176321160");
            String baseUrl =  "https://steamcommunity.com/market/listings/730/Recoil%20Case";
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 带cookie就不封
            //getItemNameIdByLink(baseUrl);

            // 不带cookie也不封
            //getVolumnByLink(baseUrl);
        }
        System.exit(1);
        String baseUrl =  "https://steamcommunity.com/market/listings/730/Recoil%20Case";
        getItemNameIdByLink(baseUrl);
        System.exit(1);
        String[] urls = new String[]{
                "https://steamcommunity.com/market/listings/730/AWP%20%7C%20The%20Prince%20%28Factory%20New%29",
                "https://steamcommunity.com/market/listings/730/Sticker%20%7C%20Bullet%20Rain",
                "https://steamcommunity.com/market/listings/730/%E2%98%85%20Specialist%20Gloves%20%7C%20Foundation%20%28Factory%20New%29",
        };
        for (String url : urls) {
            getVolumnByLink(url);
        }
        //getProxyIp(ipUrl);
    }
}

